// Datepicker
$(function(){
  
  // Using custom configuration
  $('#foo0').carouFredSel({
    width: '100%',
    scroll: 1,
    auto: true
  });
  
  /* start knippen dialog */
  $('.btn_knippen').click(function(event){
    event.preventDefault();
    pickKnippenDialog();
  });
  
  /* start knippen dialog */
  $('.home_binnenkort_butt').click(function(event){
    $("#home_binnenkort_dialog").dialog({ modal: true,  minWidth: 1010, minHeight: 400 });    
    event.preventDefault();
  });
        
  /* confirm dialog */
  $('#confirm_dialog_cancel').click(function(event){
    event.preventDefault();
    $("#confirm_dialog").dialog("close");
  });
  $('#confirm_dialog_confirm').click(function(event){
    $('#confirm_dialog_form').submit();
    event.preventDefault();
  });
 
  /* login dialog */
  $('#login_dialog_cancel').click(function(event){
    $("#login_dialog").dialog("close");
    return false;
  });
  $('#login_dialog_submit').click(function(event){
    $("#login_dialog_form").ajaxSubmit(loginDialogSubmitOptions); 
    return false;   
  });
 
  /* logout dialog */
  $('#logout_dialog_cancel').click(function(event){
    $("#logout_dialog").dialog("close");
    return false;
  });
  $('#logout_dialog_submit').click(function(event){
    $("#logout_dialog_form").ajaxSubmit(logoutDialogSubmitOptions); 
    return false;   
  });
  
  /* werkgever dialog */
  $('#werkgever_dialog_cancel').click(function(event){
    $("#werkgever_dialog").dialog("close");
    return false;
  });  
  $('#werkgever_dialog_submit').click(function(event){
    $("#werkgever_dialog_form").ajaxSubmit(werkgeverDialogSubmitOptions); 
    return false;   
  });
  
  /* generic service dialog */
  $('#generic_service_dialog_cancel').click(function(event){
    $("#generic_service_dialog").dialog("close");
    return false;
  });  
  $('#generic_service_dialog_submit').click(function(event){
    $("#generic_service_dialog_form").ajaxSubmit(genericServiceDialogSubmitOptions); 
    return false;   
  });
  
  /* auto wassen dialog */
  $('#auto_wassen_dialog_cancel').click(function(event){
    $("#auto_wassen_dialog").dialog("close");
    return false;
  });  
  $('#auto_wassen_dialog_submit').click(function(event){
    if (validateAutoWassen()) {
      $("#auto_wassen_dialog_form").submit();//.ajaxSubmit(autoWassenDialogSubmitOptions); 
    }
    return false;   
  });
  
  /* knippen dialog */
  $('#knippen_dialog_cancel').click(function(event){
    $("#knippen_dialog").dialog("close");
    return false;
  });  
  $('#knippen_dialog_submit').click(function(event){
    $("#knippen_dialog_form").submit();
    return false;   
  });
  $('#knippen_location_code').change(function(event) {
    loadKnippenDateTable();
    return false;   
  });  

  $('#car_wash_location_code').change(function(event) {
    loadCarWashDateTable();
    return false;   
  });  
  
  $(":text").labelify({labelledClass: "labelinside"});
  
  $("#main_form a.submit").click(function(event){
    event.preventDefault();
    $('#main_form').submit();    
  });
  
  $("#main_form_payment a.submit").click(function(event){
    event.preventDefault();
    $('#main_form_payment').submit();    
  });

  var main_form_ideal_action = $('#main_form_payment').attr('action');
  var main_form_contant_action = $('#main_form_contant_action').val();
  
  if ($("#payMethod1").is(':checked')) {
    $('#idealButton a').html('Klik hier om te betalen');    
    $('#main_form_payment').attr('action', main_form_ideal_action);
  } else {
    $('#idealButton a').html('Bevestig je keuze');    
    $('#main_form_payment').attr('action', main_form_contant_action);
  }
  
  $("#payMethod1").click(function(event){
    var reservation_id = $('input[name="reservation_id"]').val();
    var guid = $('input[name="guid"]').val();
  
    $.ajax("00_ajax_handle_update_pay_method.php?reservation_id=" + reservation_id + "&guid=" + guid);
    
    $('#idealButton').hide('slow');
    $('#idealButton').show('slow'); 
    $('#idealButton a').html('Klik hier om te betalen');    
    $('#main_form_payment').attr('action', main_form_ideal_action);
  });
  
  $("#payMethod2").click(function(event){
    var reservation_id = $('input[name="reservation_id"]').val();
    var guid = $('input[name="guid"]').val();
  
    $.ajax("00_ajax_handle_update_pay_method.php?reservation_id=" + reservation_id + "&guid=" + guid);
  
    $('#idealButton').hide('slow');
    $('#idealButton').show('slow'); 
    $('#idealButton a').html('Bevestig je keuze');
    $('#main_form_payment').attr('action', main_form_contant_action);
  });
  
  $(".button-stomerij").click(function(event){
    var txt = $.trim($("#user_name").text());
    if (txt == 'Aanmelden') {
      //alert('Voordat u dit formulier kunt gebruiken dient u zich eerst aan te melden!');
      loginDialog();
      return false;
    } else {
      return true;
    }
  });
  
  $("#auto-wassen-pakket-select").click(function(event){
    selectPakket($(this).val());
    return false;
  });
  $("#auto-wassen-pakket-1").click(function(event){
    selectPakket("1");
    return false;
  });
  $("#auto-wassen-pakket-2").click(function(event){
    selectPakket("2");
    return false;
  });
  $("#auto-wassen-pakket-3").click(function(event){
    selectPakket("3");
    return false;
  });
  
  $("#tabs").tabs({
     select: function(event, ui) { 
      //var t = $(e.target);
      //alert( "selected is " + ui.index );
      if (ui.index == 0) { 
        document.location.href = "02_datetime_picker.php";
        return false;
      } else if (ui.index == 1) { 
        document.location.href = "03_make_reservation.php";
        return false;
      } 
     }
  });  
  var showSubMenu = false;
  $("#menuAspr").mouseover(function(event){
    //$('#page').append('. show:' + showSubMenu);
    $('#subMenuAspr').show(); 
    $('#subMenuAspr').style.zIndex = "9999";
    showSubMenu = true;
    return false;
  });
  
  $("#subMenuAspr").mouseleave(function(event){
    //$('#page').append('. hide:' + showSubMenu);
    $('#subMenuAspr').hide(); 
    showSubMenu = false;
    return false;
  });
  
  setTimeout('rollBannerText()',2000);
  setInterval('rollBannerText()',7000);
  
  rollBannerImg();
  setInterval('rollBannerImg()',2000);
 
})

var bannerTextCurrentIndex = 1;
var bannerText = new Array(); 
bannerText[0]="KNIPPEN";
bannerText[1]="KLEREN STOMEN";
bannerText[2]="AUTO WASSEN";
//bannerText[3]="BOODSCHAPPEN BEZORGEN";
//bannerText[4]="KLUSSEN";
//bannerText[5]="STRIJKEN";

var bannerImgClassCurrentIndex = 0;
var bannerImgClass = new Array(); 
bannerImgClass[0]="knippen";
bannerImgClass[1]="stomerij";
bannerImgClass[2]="auto-wassen";
bannerImgClass[3]="boodschappen";
bannerImgClass[4]="klussen";
bannerImgClass[5]="strijken";

function rollBannerText() {
  rollBannerTextStep1();
}
function rollBannerTextStep1() {
  $('#rolling_text').fadeOut(500, function() {
    rollBannerTextStep2();
  });
} 
function rollBannerTextStep2() {
  $('#rolling_text').text(bannerText[bannerTextCurrentIndex]);
  bannerTextCurrentIndex++;
  if (bannerTextCurrentIndex == bannerText.length) {
    bannerTextCurrentIndex = 0;
  }  
  rollBannerTextStep3();
} 
function rollBannerTextStep3() {
  $('#rolling_text').fadeIn(1000);
} 
function rollBannerImg() {
  rollBannerImgStep1();
}
function rollBannerImgStep1() {
  for (var x = 0; x < bannerImgClass.length; x++)  {
    $('#rolling_img').removeClass(bannerImgClass[x]);
  }
  $('#rolling_img').addClass(bannerImgClass[bannerImgClassCurrentIndex]);
  bannerImgClassCurrentIndex++;
  if (bannerImgClassCurrentIndex == bannerImgClass.length) {
    bannerImgClassCurrentIndex = 0;
  }  
} 

var loginDialogSubmitOptions = { 
        //target:        '#error_output',   // target element(s) to be updated with server response 
        //beforeSubmit:  showRequest,  // pre-submit callback 
        success:       loginDialogSubmitSuccess  // post-submit callback 
    };
// post-submit callback 
function loginDialogSubmitSuccess(responseText, statusText, xhr, $form)  { 
    if (responseText.indexOf('error') != -1) {
      $("#login_dialog .error_output").html(responseText);  
    } else {
      if (loginRedirect != '') {
        document.location.href = loginRedirect;
      }
      $("#user_name").html(responseText);  
      $("#user_logout").show();
      $("#login_dialog .error_output").html("");  
      $("#login_dialog").dialog("close");
    }    
    return false;
} 

var logoutDialogSubmitOptions = { 
        //target:        '#error_output',   // target element(s) to be updated with server response 
        //beforeSubmit:  showRequest,  // pre-submit callback 
        success:       logoutDialogSubmitSuccess  // post-submit callback 
    };
// post-submit callback 
function logoutDialogSubmitSuccess(responseText, statusText, xhr, $form)  { 
    $("#user_name").html(responseText);  
    var url = "logout_success.php";
    //if (loginRedirect != '') {
    //  url = loginRedirect;
    //}
    document.location.href = url;
    return false;
} 

var werkgeverDialogSubmitOptions = { 
        //target:        '#error_output',   // target element(s) to be updated with server response 
        //beforeSubmit:  showRequest,  // pre-submit callback 
        success:       werkgeverDialogSubmitSuccess  // post-submit callback 
    };
// post-submit callback 
function werkgeverDialogSubmitSuccess(responseText, statusText, xhr, $form)  { 
    //$("#user_name").html(responseText);  
    alert("Hartelijk dank voor je aanmelding op RedJeZaterdag.nl! Wij nemen zo snel mogelijk contact op met je bedrijf.");
    $("#werkgever_dialog").dialog("close");
    return false;
} 

var autoWassenDialogSubmitOptions = { 
        //target:        '#error_output',   // target element(s) to be updated with server response 
        //beforeSubmit:  showRequest,  // pre-submit callback 
        success:       autoWassenDialogSubmitSuccess  // post-submit callback 
    };
// post-submit callback 
function autoWassenDialogSubmitSuccess(responseText, statusText, xhr, $form)  { 
    var arr = responseText.split("-");
    var reservation_id = arr[0];
    var guid = arr[1];
    var itemDescription1 = arr[2];
    var itemNumber1 = arr[3];
    var itemPrice1 = arr[4];
    
    $('input[name="purchaseID"]').val(reservation_id);  
    $('input[name="reservation_id"]').val(reservation_id);  
    $('input[name="guid"]').val(guid);  
    $('input[name="itemDescription1"]').val(itemDescription1);  
    $('input[name="itemNumber1"]').val(itemNumber1);  
    $('input[name="itemPrice1"]').val(itemPrice1);  
    $('input[name="amount"]').val(itemPrice1);  
    
    var idealRedirectBaseUrl = $('input[name="idealRedirectBaseUrl"]').val();  
    var params = "?reservation_id=" + reservation_id + "&guid=" + guid; 
    
    $('input[name="urlCancel"]').val(idealRedirectBaseUrl + "/ideal_cancel.php" + params);  
    $('input[name="urlSuccess"]').val(idealRedirectBaseUrl + "/ideal_success.php" + params);  
    $('input[name="urlError"]').val(idealRedirectBaseUrl + "/ideal_error.php" + params);  
    
    alert("Hartelijk dank voor je aanmelding op RedJeZaterdag.nl! Wij nemen zo snel mogelijk contact op met je bedrijf.");
    //alert("Je wordt nu doorgeleid naar iDEAL.");
    $("#auto_wassen_dialog_form_ideal").submit();
    //$("#auto_wassen_dialog").dialog("close");
    return false;
} 
    
// runs for every day displayed in datepicker, adds class and tooltip if matched to days in freeDays array
function highlightDays(date) {  
  dateText = getShortIsoDate(date);
  if (isAvaliable(dateText)) {
    if (isValid(dateText)) {
      return [true, 'avaliable-day', 'Beschikbaar']; //[0] = true | false if this day is selectable, [1] = class to add, [2] = tooltip to display
    } else {
      return [true, 'avaliable-day-past', 'Niet meer beschikbaar']; //[0] = true | false if this day is selectable, [1] = class to add, [2] = tooltip to display
    }  
  }
  return [true, ''];
}

function getShortIsoDate(date) {
  var d = date.getDate() + ''; 
  if (d.length == 1) { d = '0' + d; } 
  
  var m = (parseInt(date.getMonth()) + 1) + '';    
  if (m.length == 1) { m = '0' + m; } 
  
  return date.getFullYear() + '-' + m + '-' + d;
}

function isValid(dateText) {
  var dayNr = new Date().getDay();
  var addDays = 3;
  if (dayNr==2||dayNr==3||dayNr==4) {
    addDays = 3+2; // add weekend
  }
  var d = new Date();
  d.setDate(new Date().getDate() + addDays);  
  var todayPlus3 = getShortIsoDate(d);
  
  return (todayPlus3 < dateText);
}

function isAvaliable(dateText) {
  for ( var i=0; i<days.length; ++i ){        
    if (dateText == days[i]) {
      return true;
    }
  }
  return false;
}

function pickDateKnippen(dateText, inst) {
  if (!isValid(dateText)) {
    alert('Helaas is reserveren op deze dag niet meer mogelijk.\nKies een van de blauw gemarkeerde data om een reservering te maken.');
    $('#knippen_schedule_table').html('');
  } else if (isAvaliable(dateText)) {
    var locCode = $('#knippen_location_code').val();
    $.get('03_ajax_schedule_table.php', { schedule_date: dateText, location_code: locCode }, function(data) {
      var arr = dateText.split('-');
      $('#knippen_schedule_table').html(data);
    });      
  } else {
    alert('Helaas is deze datum niet beschikbaar voor je bedrijf.\nSelecteer een van de gemarkeerde datums.');
  }
}

function pickDateAutoWassen(dateText, inst) {
  //alert('');
  if (!isValid(dateText)) {
    alert('Helaas is reserveren op deze dag niet meer mogelijk.\nKies een van de blauw gemarkeerde data om een reservering te maken.');
  } else if (isAvaliable(dateText)) {      
    var arr = dateText.split('-');
    var txt = arr[2] + '-' + arr[1] + '-' + arr[0];
      //alert(txt);
    var reservations = rCount[dateText];
    var options = 4 - reservations;
    $("#car-count-text").html(options + " auto&#180;s");
    if (options == 0) {
      alert('Helaas deze datum is volgeboekt. Kies een andere datum.');
    } else {
      $("#auto-wassen-datum-display").val(txt);
      $("#auto-wassen-datum").val(txt);
    }
  } else {
    alert('Helaas is deze datum niet beschikbaar voor je bedrijf.\nSelecteer een van de gemarkeerde datums.');
  }
}

function changeMonthYear(year, month, inst) {
  var d = year + '-' + month + '-' + '01';
}

function cancelTimeSlot(dateText, startTime, minutes, reservation_id) {    
  id = "#" + dateText + "-" + startTime.replace(":","-");
  var arr = dateText.split('-');
  var strDate = arr[2] + '-' + arr[1] + '-' + arr[0];
  $("#confirm_dialog").attr("title", "Verwijder deze resevering");
  $("#confirm_dialog").dialog({ modal: true,  minWidth: 400 });
  
  $('input[name="date"]').val(dateText);
  $('input[name="start_time"]').val(startTime);
  $('input[name="minutes"]').val(minutes);
  $('input[name="reservation_id"]').val(reservation_id);
  $('#confirm_dialog_text').html('');
  $('#confirm_dialog_date_text').html(strDate);
  $('#confirm_dialog_start_time').html(startTime);

  $("#confirm_dialog_form").attr("action", "04_remove_reservation.php")
  $('#confirm_dialog_confirm').html("Verwijder reservering");
  $('#confirm_dialog_confirm').removeClass("make_reservation");
  $('#confirm_dialog_confirm').addClass("cancel_reservation");
  
  $(id).removeClass("BESCHIKBAAR");
  $(id).addClass("GERESERVEERD");
}

function pickTimeSlot(dateText, startTime, minutes) {    
  id = "#" + dateText + "-" + startTime.replace(":","-");
  var arr = dateText.split('-');
  var strDate = arr[2] + '-' + arr[1] + '-' + arr[0];

  $("#confirm_dialog").attr("title", "Resevering op : " + strDate + " " + startTime);
  $("#confirm_dialog").dialog({ modal: true,  minWidth: 400 });
  
  $('input[name="date"]').val(dateText);
  $('input[name="start_time"]').val(startTime);
  $('input[name="minutes"]').val(minutes);
  $('#confirm_dialog_text').html('Je reservering wordt gemaakt op onderstaande datum en tijd. Klik op bevestigen voor akkoord.');
  $('#confirm_dialog_date_text').html(strDate);
  $('#confirm_dialog_start_time').html(startTime);

  $("#confirm_dialog_form").attr("action", "03_make_reservation.php");
  $('#confirm_dialog_confirm').html("Bevestigen");
  $('#confirm_dialog_confirm').removeClass("cancel_reservation");
  $('#confirm_dialog_confirm').addClass("make_reservation");
  
  $(id).removeClass("BESCHIKBAAR");
  $(id).addClass("GERESERVEERD");
}

function loginDialog() {    
  $("#login_dialog").dialog({ modal: true,  minWidth: 400 });
}
function logoutDialog() {    
  $("#logout_dialog").dialog({ modal: true,  minWidth: 400 });
}
function pickWerkgeverDialog() {    
  $("#werkgever_dialog").dialog({ modal: true,  minWidth: 500, minHeight: 400 });
}
function genericServiceDialog(serviceText) {    
  $.get('00_ajax_is_logged_in.php', function(data) {
    var loggedIn = (data=='true');
    if (loggedIn) {
      $("#generic_service_dialog_service_text").html(serviceText);
      $("#generic_service_dialog").dialog({ modal: true,  minWidth: 400 });
    } else {
      loginDialog();
    }
  });
}

function loadKnippenDateTable() {    
  $('#knippen_date_table').html('');
  $('#knippen_schedule_table').html('');

  var locCode = $('#knippen_location_code').val();
  //alert(locCode);
  
  $.get('03_ajax_date_table.php', { location_code: locCode }, function(data) {
    $('#knippen_date_table').html(data);
  });      

  /*
  $.getJSON('00_ajax_available_days.php?location_code='+ locCode +'&jsoncallback=?', function(data) {
    days = new Array();
    $.each(data, function(key, val) {
      days[key] = val;
      //alert(key);
    });
    //      for (var i=0; i<data.length; i++) {
    //        days = new Array();
    //        days[i] = data[0];
    //      }
  });
  */
}
function loadCarWashDateTable() {    
  $('#car_wash_date_table').html('');

  var locCode = $('#car_wash_location_code').val();
  //alert(locCode);
  
  $.get('23_ajax_date_table.php', { location_code: locCode }, function(data) {
    $('#car_wash_date_table').html(data);
  });      
}

function pickKnippenDialog() { 
  $.get('00_ajax_is_logged_in.php', function(data) {
    var loggedIn = (data=='true');
    if (loggedIn) {
      $("#knippen_dialog").dialog({ modal: true,  minWidth: 960, minHeight: 500 });
    } else {
      loginDialog();
    }
  });
}
function pickAutoWassenDialog() { 
  $.get('00_ajax_is_logged_in.php', function(data) {
    var loggedIn = (data=='true');
    if (loggedIn) {
      $("#auto_wassen_dialog").dialog({ modal: true,  minWidth: 960, minHeight: 600 });
    } else {
      loginDialog();
    }
  });
}
function selectPakket(optionValue) {
  $("#auto-wassen-pakket-select").val(optionValue);
  $("#auto-wassen-pakket-1 img").attr("src","img/auto-wassen-pakket-1" + ((optionValue=="1") ? "-sel" : "") + ".png");
  $("#auto-wassen-pakket-2 img").attr("src","img/auto-wassen-pakket-2" + ((optionValue=="2") ? "-sel" : "") + ".png");
  $("#auto-wassen-pakket-3 img").attr("src","img/auto-wassen-pakket-3" + ((optionValue=="3") ? "-sel" : "") + ".png");
}

function validateAutoWassen() {
  var e = null;
  
  e = $('input[name="auto_wassen_datum"]');
  var datum = e.val();
  if (datum.length == 0 || isNaN(datum.substr(0,2)) ) {
    alert("De datum is niet of niet juist ingevuld.");
    $("#datepicker_car_wash div.ui-datepicker").addClass("error");
    return false;
  } else {
    $("#datepicker_car_wash div.ui-datepicker").removeClass("error");
  }
  
  e = $('select[name="auto_wassen_pakket"]');
  var pakket = e.val();
  if (pakket.length == 0 || pakket == "0" || isNaN(pakket.substr(0,1)) ) {
    alert("Het pakket is niet of niet juist ingevuld");
    e.addClass("error");
    return false;
  } else {
    e.removeClass("error");
  }
  
  e = $('input[name="auto_wassen_name1"]');
  var name1 = e.val();
  
  e = $('input[name="auto_wassen_tel_number"]');
  var tel = e.val();
  if (tel.length == 0 || tel.length < 10 || isNaN(tel.substr(0,2)) ) {
    alert("Het telefoonnummer is niet of niet juist ingevuld.");
    e.addClass("error");
    return false;
  } else {
    e.removeClass("error");
  }
  
  e = $('input[name="auto_wassen_kenteken_auto"]');  
  var kenteken = e.val();
  if (kenteken.length < 8 || kenteken.length > 9) {
    alert("Het kenteken is niet of niet juist ingevuld.");
    e.addClass("error");
    return false;
  } else {
    e.removeClass("error");
  }

  return true;
}
